package tank;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

import abstractBeanFactory.BaseBullet;
import abstractBeanFactory.BaseTank;

public class Bullet extends BaseBullet {
	private static final int SPEED =6;
	public static final int width =ResourceMgr.bulletD.getWidth();
	public static final int height =ResourceMgr.bulletD.getHeight();
	private int x,y;
	private Dir dir;
	private boolean living = true;
	private TankFrame tf=null;
	private Group group = Group.BAD;
	Rectangle rect = new Rectangle();
	public Group getGroup() {
		return group;
	}
	public void setGroup(Group group) {
		this.group = group;
	}
	public Bullet(int x,int y,Dir dir,Group group,TankFrame tf) {
		this.x =x;
		this.y =y;
		this.dir =dir;
		this.tf =tf;
		this.group = group;
		rect.x= this.x;
		rect.y= this.y;
		rect.width= this.width;
		rect.height= this.height;
		tf.bullets.add(this);
	}
	// 碰撞检测
	public void collideWith(BaseTank tank) {
		if(this.group == tank.getGroup())return;
		//使用一个rect，来记录子弹和tank的位置（需要优化）
//		Rectangle bulletRec = new Rectangle(this.x,this.y,width,height);
//		Rectangle tankRec = new Rectangle(tank.getX(),tank.getY(),tank.TANK_WIDTH,tank.TANK_HEIGHT);
		if(rect.intersects(tank.rect)) {
			tank.die();
			this.die();
			int ex = tank.getX()+Tank.TANK_WIDTH/2-Explode.WIDTH/2;
			int ey = tank.getY()+Tank.TANK_HEIGHT/2-Explode.HEIGHT/2;
			tf.explodes.add(tf.abstractTankBeanFactory.creatExplode(ex, ey, tf));
		}
		
	}
	private void die() {
		// TODO Auto-generated method stub
		this.living =false;
	}
	private void move() {
		switch (dir) {
		case LEFT:
			x-=SPEED;
			break;
		case UP:
			y-=SPEED;
			break;
		case RIGHT:
			x+=SPEED;
			break;
		case DOWN:
			y+=SPEED;
			break;

		default:
			break;
		}
		rect.x=this.x;
		rect.y=this.y;
		if(x<=0||y<=0||x>TankFrame.GAME_WIDTH||y>TankFrame.GAME_HEIGHT) {
			living =false;
		}
	}
	@Override
	public void paint(Graphics g) {
		if(!living)this.tf.bullets.remove(this);
//		Color color = g.getColor();
//		g.setColor(Color.RED);
//		g.fillOval(x, y, width, height);
//		g.setColor(color);
		switch (dir) {
		case LEFT:
			g.drawImage(ResourceMgr.bulletL, x, y, null);
			break;
		case UP:
			g.drawImage(ResourceMgr.bulletU, x, y, null);
			break;
		case RIGHT:
			g.drawImage(ResourceMgr.bulletR, x, y, null);
			break;
		case DOWN:
			g.drawImage(ResourceMgr.bulletD, x, y, null);
			break;
		default:
			break;
		}
		move();
	}
}
